package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.Resp.BaseResp;
import com.qf.dao.GoodsRespository;
import com.qf.goods.Goods;
import com.qf.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author H
 * @create 2020-11-03 11:47
 * @strive To be whoever you want to be.
 * @Description:
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    GoodsRespository goodsRespository;

    @Override
    public BaseResp findAllGoods() {
        BaseResp baseResp = new BaseResp();
        Boolean good_list = redisTemplate.hasKey("good_list");
        if (good_list) {
            List good_list1 = redisTemplate.opsForList().range("good_list", 0, -1);
            baseResp.setCode(200l);
            baseResp.setMessage(good_list1);
            return baseResp;
        } else {
            List<Goods> all = goodsRespository.findAll();
            Object o = JSONObject.toJSON(all);
            redisTemplate.opsForList().leftPushAll("good_list", all);
            redisTemplate.expire("good_list", 60, TimeUnit.MINUTES);
            baseResp.setCode(200l);
            baseResp.setMessage(all);
            return baseResp;
        }
    }

    @Override
    public Goods findById(Integer id) {
        return goodsRespository.findById(id).get();
    }
}

